package zld369504.tw.m_team;


import android.text.TextUtils;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.dao.Torrent;
import zld369504.tw.m_team.dao.TorrentDetail;
import zld369504.tw.m_team.dao.User;

public class DataParser {

    public static boolean parseUserBriefInfoFromMainPageSide(String bodyString) {
        try {
            Document document = Jsoup.parse(bodyString);
            Element personalBriefInfo = document.getElementById("info_block");
            Element e_userInfo = personalBriefInfo.getElementsByAttributeValueContaining("href", "userdetails.php?id=").get(0);
            String userName = e_userInfo.text();
            String uid = e_userInfo.attr("href").substring(e_userInfo.attr("href").indexOf("=") + 1);
            User user = User.getInstance();
            user.setUserName(userName);
            user.setUserId(Integer.parseInt(uid));

            Element otherInfoMain = personalBriefInfo.getElementsByClass("bottom").get(0).child(0);

            List<Node> nodeList = otherInfoMain.childNodes();
            for (int i = 0; i < nodeList.size(); i++) {
                Node node = nodeList.get(i);
                if (node instanceof Element) {
                    Element ee = (Element) node;
                    if (ee.tagName().equals("a") && ee.attr("href").contains("mybonus.php")) {
                        Node magicBonusNode = nodeList.get(i + 1);
                        if (magicBonusNode instanceof TextNode) {
                            String magicBonusRaw = ((TextNode) magicBonusNode).text();
                            String magicBonus = magicBonusRaw.replace("]:", "").trim();
                            user.setMagicCount(magicBonus);
                        }
                    } else if(ee.tagName().equals("font")){
                        if("color_ratio".equals(ee.className())){
                            Node ratioNode = nodeList.get(i + 1);
                            if (ratioNode instanceof TextNode) {
                                String ratio = ((TextNode) ratioNode).text().trim();
                                user.setSharePoint(ratio);
                            }
                        } else if("color_uploaded".equals(ee.className())){
                            Node uploadNode = nodeList.get(i + 1);
                            if (uploadNode instanceof TextNode) {
                                String upload = ((TextNode) uploadNode).text().trim();
                                user.setUploadCount(upload);
                            }
                        } else if("color_downloaded".equals(ee.className())){
                            Node downloadNode = nodeList.get(i + 1);
                            if (downloadNode instanceof TextNode) {
                                String download = ((TextNode) downloadNode).text().trim();
                                user.setDownloadCount(download);
                            }
                        }
                    }
                }


            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static List<Torrent> parseTorrentList(String bodyString) {
        List<Torrent> list = new ArrayList<>();
        Document root = Jsoup.parse(bodyString);
        root.setBaseUri(MTeamHttpsApiImpl.baseUrl);
        Elements torrentsElement = root.getElementsByClass("torrents");
        if (torrentsElement.size() != 0) {
            //有种子存在。如果没了这个判断，当页面上没有种子就会报错IndexOutOfBoundsException
            Element torrentsRaw = torrentsElement.get(0);//table
            Elements torrentsListRaw = torrentsRaw.child(0).children();
            for (int i = 1; i < torrentsListRaw.size(); i++) {//列表第二个元素才是种子的数据
                Torrent torrent = new Torrent();

                //检查是否置顶
                Element isStickTopElement = torrentsListRaw.get(i);
                if (!TextUtils.isEmpty(isStickTopElement.className())) {
                    if ("sticky_top".equals(isStickTopElement.className())) {
                        torrent.setStickyTopLevel(2);
                    } else if ("sticky_normal".equals(isStickTopElement.className())) {
                        torrent.setStickyTopLevel(1);
                    }
                } else {
                    torrent.setStickyTopLevel(0);
                }

                Elements torrentE = torrentsListRaw.get(i).children();

                for (int j = 0; j < torrentE.size(); j++) {
                    Element ee = torrentE.get(j);
                    switch (j) {
                        case 0://类型
                            Element ee0 = ee.child(0);
                            String typeStrInt = ee0.attr("href").substring(ee0.attr("href").indexOf("=") + 1);
                            torrent.setTypeInt(Integer.parseInt(typeStrInt));
                            Element ee00 = ee0.child(0);
                            String typePic = ee00.attr("style");
                            //style="background-image: url(pic/category/chd/scenetorrents/cht/moviehd.png);"
                            typePic = MTeamHttpsApiImpl.baseUrl + "/" + typePic.substring(typePic.indexOf("(") + 1, typePic.indexOf(")"));
                            torrent.setTypePicUrl(typePic);
                            String typeText = ee00.attr("alt");
                            torrent.setTypeName(typeText);
                            break;
                        case 1:
                            Element ee1 = ee.getElementsByClass("torrentname").get(0);
                            //种子图片
                            Element torrentPicElement = ee1.getElementsByClass("torrentimg").get(0).child(0).child(0);
                            String torrentImgUrl = torrentPicElement.attr("src");
                            if (torrentImgUrl.startsWith("http://") || torrentImgUrl.startsWith("https://")) {
                                torrent.setImageUrl(torrentImgUrl);
                            } else {
                                torrent.setImageUrl(torrentPicElement.attr("abs:src"));
                            }
                            //是否为官方种+种子名称+副标题
                            Element embeddedElement = ee1.child(0).child(0).child(1);
                            Elements count = embeddedElement.children();
                            boolean official = false;
                            boolean hasTitleOfSubTitle = false;
                            boolean hasDiscountTimeLeft = false;
                            for (Element e : count) {
                                if (e.tagName().equals("img")) {
                                    if (e.attr("src").equals("pic/ms_up.gif")) {
                                        //官方字段
                                        official = true;
                                    } else if (!TextUtils.isEmpty(e.className()) && e.className().startsWith("pro_")) {
                                        //优惠字段
                                        if ("pro_free".equals(e.className())) {
                                            //优惠-免费
                                            torrent.setDiscount(100);
                                        } else if ("pro_50pctdown".equals(e.className())) {
                                            //优惠-50%
                                            torrent.setDiscount(50);
                                        } else if ("pro_30pctdown".equals(e.className())) {
                                            //优惠-30%
                                            torrent.setDiscount(30);
                                        } else {
                                            //没优惠
                                            torrent.setDiscount(0);
                                        }
                                    } else if (!TextUtils.isEmpty(e.className()) && e.className().startsWith("label_")) {
                                        //NexusPHP的作者？在制作国语配音的元素时候手误？故意？把label_sub打成了label_dub....坑爹！
                                        //中文字幕字段+国语配音
                                        if ("中字".equals(e.attr("alt"))) {
                                            torrent.setIncludeChineseSubtitle(true);
                                        } else if ("國配".equals(e.attr("alt"))) {
                                            torrent.setIncludeChineseTrack(true);
                                        } else if ("DIY".equals(e.attr("alt"))) {
                                            torrent.setDiy(true);
                                        }
                                    }
                                } else if (e.tagName().equals("a")) {
                                    //种子名称
                                    Element e_torrentTitle = e.child(0);
                                    String title = e_torrentTitle.text();
                                    torrent.setTitle(title);
                                    //种子id
                                    String idStr = e.attr("href");
                                    //details.php?id=220542&hit=1
                                    torrent.setTorrentId(Integer.parseInt(idStr.substring(idStr.indexOf("=") + 1, idStr.indexOf("&"))));
                                } else if (e.tagName().equals("br")) {
                                    //种子有副标题
                                    List<Node> nodeList = embeddedElement.childNodes();
                                    for (int k = 0; k < nodeList.size(); k++) {
                                        String nodeName = nodeList.get(k).nodeName();
                                        if ("br".equals(nodeName)) {
                                            hasTitleOfSubTitle = true;
                                            if (k == nodeList.size() - 1) {
                                                //br是最后一个元素
                                                torrent.setSubTitle("");
                                            } else if (k < nodeList.size() - 1) {
                                                torrent.setSubTitle(nodeList.get(k + 1).toString());
                                            }
                                            break;
                                        }
                                    }
                                } else if ("span".equals(e.tagName()) && "font-weight:normal".equals(e.attr("style"))) {
                                    String limitTime = e.text().trim();
                                    hasDiscountTimeLeft = true;
                                    torrent.setDiscountTimeLeft(limitTime);
                                } else if ("b".equals(e.tagName())) {
                                    Elements elementsHot = e.getElementsByClass("hot");
                                    if (elementsHot.size() != 0) {
                                        torrent.setHot(true);
                                    } else {
                                        torrent.setHot(false);
                                    }
                                    Elements elementsNew = e.getElementsByClass("new");
                                    if (elementsNew.size() != 0) {
                                        torrent.setNewTorrent(true);
                                    } else {
                                        torrent.setNewTorrent(false);
                                    }
                                }
                            }
                            //是否为官方种
                            torrent.setOfficial(official);
                            if (!hasTitleOfSubTitle) {
                                torrent.setSubTitle("");
                            }
                            if (!hasDiscountTimeLeft) {
                                torrent.setDiscountTimeLeft("");
                            }
                            break;
                        case 3:
                            //ttlTime
                            String ttlTime = ee.text();
                            torrent.setTtlTime(ttlTime);
                            torrent.setReleaseTime(ee.child(0).attr("title"));
                            break;
                        case 4:
                            //size
                            torrent.setSize(ee.text());
                            break;
                        case 5:
                            //upload
                            torrent.setUploadingCount(Integer.parseInt(ee.text().replace(",", "").trim()));
                            break;
                        case 6:
                            //download
                            torrent.setDownloadingCount(Integer.parseInt(ee.text().replace(",", "").trim()));
                            break;
                        case 7:
                            //finish
                            torrent.setFinishedCount(Integer.parseInt(ee.text().replace(",", "").trim()));
                            break;
                    }
                }
                list.add(torrent);
            }
        }
        return list;
    }

    public static TorrentDetail parseTorrentDetail(String bodyString, boolean isAdult) {
        TorrentDetail torrentDetail = new TorrentDetail();
        torrentDetail.setAdult(isAdult);
        Document root = Jsoup.parse(bodyString);
        root.setBaseUri(MTeamHttpsApiImpl.baseUrl);

        if (!isAdult) {
            //imdb
            Element torrentImdbInfo = root.getElementById("kimdb");
            if (torrentImdbInfo != null) {
                torrentDetail.setImdbInfo(torrentImdbInfo.html());
            }
        } else {
            //成人片没有imdb，可能有dmm
            //dmm
            Elements dmmTypeElements = root.getElementsByClass("dmm_type");
            if (dmmTypeElements != null && dmmTypeElements.size() != 0) {
                TorrentDetail.DMMInfo dmmInfo = new TorrentDetail.DMMInfo();
                //搜索封面图片
                Element dmmTypeElement = dmmTypeElements.get(0);
                Elements dmmTypeChildElements = dmmTypeElement.children();
                for (Element dmmtype : dmmTypeChildElements) {
                    if ("img".equals(dmmtype.tagName())) {
                        // 封面图片
                        dmmInfo.setCoverSmallImageUrl(dmmtype.attr("abs:src"));
                        String largeImageUrlMux = dmmtype.attr("onclick");
                        dmmInfo.setCoverLargeImageUrl(largeImageUrlMux.substring(largeImageUrlMux.indexOf("'") + 1, largeImageUrlMux.lastIndexOf("'")));
                    } else if ("table".equals(dmmtype.tagName())) {
                        Elements tableElements = dmmtype.child(0).children();
                        LinkedHashMap<String, String> map = new LinkedHashMap<>();
                        for (int i = 0; i < tableElements.size(); i++) {
                            Element tableRow = tableElements.get(i);
                            if (tableRow.children().size() == 2) {
                                // FIXME: 2018/1/9 这里有个评分的东西，是个图片，暂时不做解析
                                map.put(tableRow.child(0).text(), tableRow.child(1).text());
                            } else if (tableRow.children().size() == 1) {
                                map.put(tableRow.child(0).text(), "");
                            }
                        }
                        dmmInfo.setBriefInfo(map);
                    }
                }
                Element dmmTextElement = root.getElementsByClass("dmm_text").get(0);
                dmmInfo.setText(dmmTextElement.text().trim());
                Elements dmmPicElements = root.getElementsByClass("dmm_pic");
                if (dmmPicElements != null && dmmPicElements.size() != 0) {
                    Element dmmPicElement = dmmPicElements.first();
                    List<LinkedHashMap<String, String>> list = new ArrayList<>();
                    for (Element subElement : dmmPicElement.children()) {
                        String small = subElement.attr("abs:src");
                        String largeMix = subElement.attr("onclick");
                        String large = largeMix.substring(largeMix.indexOf("'") + 1, largeMix.lastIndexOf("'"));
                        LinkedHashMap<String, String> map = new LinkedHashMap<>();
                        map.put("small", small);
                        map.put("large", large);
                        list.add(map);
                    }
                    dmmInfo.setScreenshotPicUrlList(list);
                }
                torrentDetail.setDmmInfo(dmmInfo);
            }// else : no dmm info found
        }

        //简介
        Element torrentDescription = root.getElementById("kdescr");
        if (torrentDescription != null) {

            Elements todoRemoveAttrs = torrentDescription.getElementsByTag("img");
            for (Element e : todoRemoveAttrs) {
                e.removeAttr("onclick")
                        .removeAttr("onload")
                        .attr("width", "100%")
                        .attr("height", "auto");
            }
            torrentDetail.setDescription(torrentDescription.html());
        }

        Element mainDescElement = root.getElementById("outer");
        if (mainDescElement != null) {

            //基本信息
            Element basicInfoElement = parseTorrentBasicInfo(mainDescElement.getElementsByTag("table").first().child(0));
            if (basicInfoElement != null) {
                //取出文本部分
                List<TextNode> textNodeList = basicInfoElement.textNodes();//value
                Elements childNodeList = basicInfoElement.children();//key

                LinkedHashMap<String, String> map = new LinkedHashMap<>();
                for (int i = 0; i < childNodeList.size(); i++) {
                    String key = childNodeList.get(i).text().trim();
                    String value = textNodeList.get(i).toString().replace("&nbsp;", "").trim();
                    map.put(key, value);
                }
                torrentDetail.setBasicInfo(map);
            }

            //种子下载地址
            //Torrent URL
            Element tDownloadElement = parseTorrentDownloadInfo(mainDescElement.getElementsByTag("table").first().child(0));
            Element td = tDownloadElement.children().last();
            for (Element e1 : td.children()) {
                if (e1.text().equals("[IPv4+https]")) {
                    torrentDetail.setIpv4HttpsTorrentUrl(e1.attr("abs:href"));
                } else if (e1.text().equals("[IPv6+https]")) {
                    torrentDetail.setIpv6HttpsTorrentUrl(e1.attr("abs:href"));
                }
            }

        }
        return torrentDetail;
    }

    /**
     * 解析种子的基本信息
     *
     * @param rootElement 待解析的元素
     * @return 包含基本信息的element
     */
    private static Element parseTorrentBasicInfo(Element rootElement) {
        //rootElement is <tbody>
        Elements elements = rootElement.children();
        for (Element e : elements) {
            String text = e.child(0).text().trim();
            if ("基本資訊".equals(text) || "Basic Info".equals(text)) {
                return e.child(1);
            }
        }
        return null;
    }

    private static Element parseTorrentDownloadInfo(Element rootElement) {
        //rootElement is <tbody>
        Elements elements = rootElement.children();
        for (Element e : elements) {
            String text = e.child(0).text().trim();
            if ("種子鏈接".equals(text) || "Torrent URL".equals(text)) {
                return e.child(1);
            }
        }
        return null;
    }
}
